package com.basessm.redis.core;

import java.io.Serializable;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.commons.lang3.SerializationUtils;
import org.apache.ibatis.cache.Cache;

import redis.clients.jedis.Jedis;

public class RedisCache implements Cache{
	
	private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
	private Jedis jedis;
	private String id;

	public RedisCache(final String id) {
		if (id == null) {
			throw new IllegalArgumentException("必须传入ID");
		}
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id=" + id);
		this.id = id;
	}
	 
	
	@Override
	public void clear() {
		jedis.flushAll();
	}

	@Override
	public String getId() {
		return "REDIS CACHE";
	}

	@Override
	public Object getObject(Object key) {
		byte[] bs = jedis.get(SerializationUtils.serialize((Serializable)key));
		if (bs == null) {
			return null;
		}
		return SerializationUtils.deserialize(bs);
	}

	@Override
	public ReadWriteLock getReadWriteLock() {
		return readWriteLock;
	}

	@Override
	public int getSize() {
		// 默认0号数据库
		return 0;
	}

	@Override
	public void putObject(Object key, Object value) {
		jedis.set(SerializationUtils.serialize((Serializable)key), SerializationUtils.serialize((Serializable)value));
	}

	@Override
	public Object removeObject(Object key) {
		byte[] bs = jedis.get(SerializationUtils.serialize((Serializable)key));
		jedis.del(SerializationUtils.serialize((Serializable)key));
		return SerializationUtils.deserialize(bs);
	}

}
